package com.yuanqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.dto.SalesReturnOrderDTO;
import com.yuanqi.dto.SalesReturnOrderItemDTO;
import com.yuanqi.dto.SalesReturnOrderQueryDTO;
import com.yuanqi.mapper.SalesReturnOrderAuditMapper;
import com.yuanqi.mapper.SalesReturnOrderItemMapper;
import com.yuanqi.mapper.SalesReturnOrderMapper;
import com.yuanqi.pojo.SalesReturnOrder;
import com.yuanqi.pojo.SalesReturnOrderAudit;
import com.yuanqi.pojo.SalesReturnOrderItem;
import com.yuanqi.service.SalesReturnOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 销售退货订单Service实现类
 */
@Slf4j
@Service
public class SalesReturnOrderServiceImpl implements SalesReturnOrderService {

    @Resource
    private SalesReturnOrderMapper salesReturnOrderMapper;

    @Resource
    private SalesReturnOrderItemMapper salesReturnOrderItemMapper;

    @Resource
    private SalesReturnOrderAuditMapper salesReturnOrderAuditMapper;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addReturnOrder(SalesReturnOrderDTO returnOrderDTO) {
        // 生成退货单编号
        String returnNo = generateReturnNo();
        
        // 创建退货订单实体
        SalesReturnOrder returnOrder = new SalesReturnOrder();
        BeanUtils.copyProperties(returnOrderDTO, returnOrder);
        returnOrder.setReturnNo(returnNo);
        returnOrder.setCreateTime(LocalDateTime.now());
        returnOrder.setStatus(0); // 草稿状态
        
        // 设置默认创建人ID
        returnOrder.setCreatorId(1L);
        
        // 计算总退货金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        if (returnOrderDTO.getItems() != null) {
            for (SalesReturnOrderItemDTO item : returnOrderDTO.getItems()) {
                totalAmount = totalAmount.add(item.getReturnAmount());
            }
        }
        returnOrder.setTotalReturnAmount(totalAmount);
        
        // 保存退货订单
        salesReturnOrderMapper.insert(returnOrder);
        
        // 保存退货明细
        if (returnOrderDTO.getItems() != null && !returnOrderDTO.getItems().isEmpty()) {
            List<SalesReturnOrderItem> items = returnOrderDTO.getItems().stream()
                    .map(itemDTO -> {
                        SalesReturnOrderItem item = new SalesReturnOrderItem();
                        BeanUtils.copyProperties(itemDTO, item);
                        item.setReturnOrderId(returnOrder.getId());
                        return item;
                    })
                    .collect(Collectors.toList());
            
            salesReturnOrderItemMapper.batchInsert(items);
        }
        
        log.info("新增销售退货订单成功，退货单号：{}", returnNo);
        return returnOrder.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteReturnOrder(Long id) {
        // 检查是否可以删除
        if (!canDelete(id)) {
            throw new RuntimeException("当前状态不允许删除");
        }
        
        // 删除退货明细
        salesReturnOrderItemMapper.deleteByReturnOrderId(id);
        
        // 删除退货订单
        int result = salesReturnOrderMapper.deleteById(id);
        
        log.info("删除销售退货订单，ID：{}，结果：{}", id, result > 0);
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReturnOrder(SalesReturnOrderDTO returnOrderDTO) {
        // 检查是否可以编辑
        if (!canEdit(returnOrderDTO.getId())) {
            throw new RuntimeException("当前状态不允许编辑");
        }
        
        // 更新退货订单
        SalesReturnOrder returnOrder = new SalesReturnOrder();
        BeanUtils.copyProperties(returnOrderDTO, returnOrder);
        
        // 计算总退货金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        if (returnOrderDTO.getItems() != null) {
            for (SalesReturnOrderItemDTO item : returnOrderDTO.getItems()) {
                totalAmount = totalAmount.add(item.getReturnAmount());
            }
        }
        returnOrder.setTotalReturnAmount(totalAmount);
        
        int result = salesReturnOrderMapper.updateById(returnOrder);
        
        // 更新退货明细
        if (returnOrderDTO.getItems() != null) {
            // 先删除原有明细
            salesReturnOrderItemMapper.deleteByReturnOrderId(returnOrderDTO.getId());
            
            // 重新插入明细
            if (!returnOrderDTO.getItems().isEmpty()) {
                List<SalesReturnOrderItem> items = returnOrderDTO.getItems().stream()
                        .map(itemDTO -> {
                            SalesReturnOrderItem item = new SalesReturnOrderItem();
                            BeanUtils.copyProperties(itemDTO, item);
                            item.setReturnOrderId(returnOrderDTO.getId());
                            return item;
                        })
                        .collect(Collectors.toList());
                
                salesReturnOrderItemMapper.batchInsert(items);
            }
        }
        
        log.info("更新销售退货订单，ID：{}，结果：{}", returnOrderDTO.getId(), result > 0);
        return result > 0;
    }

    @Override
    public SalesReturnOrderDTO getReturnOrderDetail(Long id) {
        SalesReturnOrderDTO returnOrderDTO = salesReturnOrderMapper.selectDetailById(id);
        if (returnOrderDTO != null) {
            
            // 查询退货明细
            List<SalesReturnOrderItem> items = salesReturnOrderItemMapper.selectByReturnOrderId(id);
            List<SalesReturnOrderItemDTO> itemDTOs = items.stream()
                    .map(item -> {
                        SalesReturnOrderItemDTO itemDTO = new SalesReturnOrderItemDTO();
                        BeanUtils.copyProperties(item, itemDTO);
                        return itemDTO;
                    })
                    .collect(Collectors.toList());
            returnOrderDTO.setItems(itemDTOs);
        }
        return returnOrderDTO;
    }

    @Override
    public IPage<SalesReturnOrderDTO> getReturnOrderPage(SalesReturnOrderQueryDTO queryDTO) {
        Page<SalesReturnOrderDTO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        IPage<SalesReturnOrderDTO> result = salesReturnOrderMapper.selectPage(page, queryDTO);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitForAudit(Long id) {
        SalesReturnOrder returnOrder = salesReturnOrderMapper.selectById(id);
        if (returnOrder == null) {
            throw new RuntimeException("退货订单不存在");
        }
        
        if (returnOrder.getStatus() != 0) {
            throw new RuntimeException("只有草稿状态的退货订单才能提交审核");
        }
        
        // 更新状态为待审核
        returnOrder.setStatus(1);
        int result = salesReturnOrderMapper.updateById(returnOrder);
        
        log.info("提交销售退货订单审核，ID：{}，结果：{}", id, result > 0);
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditReturnOrder(Long id, Integer auditResult, String auditOpinion, Long auditorId) {
        SalesReturnOrder returnOrder = salesReturnOrderMapper.selectById(id);
        if (returnOrder == null) {
            throw new RuntimeException("退货订单不存在");
        }
        
        if (returnOrder.getStatus() != 1) {
            throw new RuntimeException("只有待审核状态的退货订单才能审核");
        }
        
        // 创建审核记录
        SalesReturnOrderAudit audit = new SalesReturnOrderAudit();
        audit.setReturnOrderId(id);
        audit.setAuditorId(auditorId);
        audit.setAuditTime(LocalDateTime.now());
        audit.setAuditOpinion(auditOpinion);
        audit.setAuditResult(auditResult);
        salesReturnOrderAuditMapper.insert(audit);
        
        // 更新退货订单状态
        returnOrder.setStatus(auditResult == 1 ? 2 : 0); // 通过为2，驳回为0
        returnOrder.setAuditorId(auditorId);
        returnOrder.setAuditTime(LocalDateTime.now());
        returnOrder.setAuditOpinion(auditOpinion);
        
        int result = salesReturnOrderMapper.updateById(returnOrder);
        
        log.info("审核销售退货订单，ID：{}，结果：{}，审核结果：{}", id, result > 0, auditResult);
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeReturnOrder(Long id) {
        SalesReturnOrder returnOrder = salesReturnOrderMapper.selectById(id);
        if (returnOrder == null) {
            throw new RuntimeException("退货订单不存在");
        }
        
        if (returnOrder.getStatus() != 2) {
            throw new RuntimeException("只有审核通过的退货订单才能完成");
        }
        
        // 更新状态为已完成
        returnOrder.setStatus(3);
        int result = salesReturnOrderMapper.updateById(returnOrder);
        
        log.info("完成销售退货订单，ID：{}，结果：{}", id, result > 0);
        return result > 0;
    }

    @Override
    public List<SalesReturnOrder> getReturnOrdersByOrderId(Long orderId) {
        return salesReturnOrderMapper.selectByOrderId(orderId);
    }

    @Override
    public String generateReturnNo() {
        // 生成退货单编号：SRO_yyyyMMdd_xxx
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        
        // 查询当天最大编号
        LambdaQueryWrapper<SalesReturnOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(SalesReturnOrder::getReturnNo, "SRO_" + dateStr)
                .orderByDesc(SalesReturnOrder::getReturnNo)
                .last("LIMIT 1");
        
        SalesReturnOrder maxOrder = salesReturnOrderMapper.selectOne(wrapper);
        
        int sequence = 1;
        if (maxOrder != null && maxOrder.getReturnNo() != null) {
            String[] parts = maxOrder.getReturnNo().split("_");
            if (parts.length == 3) {
                try {
                    sequence = Integer.parseInt(parts[2]) + 1;
                } catch (NumberFormatException e) {
                    sequence = 1;
                }
            }
        }
        
        return String.format("SRO_%s_%03d", dateStr, sequence);
    }

    @Override
    public boolean canDelete(Long id) {
        SalesReturnOrder returnOrder = salesReturnOrderMapper.selectById(id);
        if (returnOrder == null) {
            return false;
        }
        // 只有草稿状态可以删除
        return returnOrder.getStatus() == 0;
    }

    @Override
    public boolean canEdit(Long id) {
        SalesReturnOrder returnOrder = salesReturnOrderMapper.selectById(id);
        if (returnOrder == null) {
            return false;
        }
        // 只有草稿状态可以编辑
        return returnOrder.getStatus() == 0;
    }
}

